package postgres

import (
	"auth/model"
	"auth/model/entity"
)

var Menu = &menu{}

type menu struct{}

func (a *menu) Create(m *entity.Menu) (int64, error) {
	err := db.Create(m).Error
	return m.ID, err
}

func (a *menu) FindByParameter(in *model.MenuInfo) (*entity.Menu, error) {
	var (
		err    error
		q      = db.Model(&entity.Menu{})
		entity entity.Menu
	)
	if in.Name != "" {
		q = q.Where("name = ?", in.Name)
	}
	if in.ParentId > 0 {
		q = q.Where("parent_id = ?", in.ParentId)
	}
	err = q.First(&entity).Error
	return &entity, err
}

func (a *menu) IsExistSameName(menuId int64, name string) error {
	return db.Where("id <> ? AND name = ?", menuId, name).First(&entity.Menu{}).Error
}

func (a *menu) Find(id int64) (*entity.Menu, error) {
	e := &entity.Menu{}
	err := db.Model(&entity.Menu{}).Find(&e, id).Error
	return e, err
}

func (a *menu) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.Menu{}).Where("id = ?", id).Updates(dict).Error
}

func (a *menu) Delete(id int64) error {
	return db.Delete(&entity.Menu{}, id).Error
}

func (a *menu) List(in *model.MenuListRequest) (int, []*entity.Menu, error) {
	var (
		q     = db.Model(&entity.Menu{})
		err   error
		total int64
		menus []*entity.Menu
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&menus).Error; err != nil {
		return 0, nil, err
	}
	return int(total), menus, nil
}

func (a *menu) GetBaseMenuTreeMap() ([]*entity.Menu, error) {
	var (
		err      error
		allMenus []*entity.Menu
	)
	err = db.Order("sort").Find(&allMenus).Error
	return allMenus, err
}

func (a *menu) FindByIds(ids []int64) ([]*entity.Menu, error) {
	var (
		err       error
		listMenus []*entity.Menu
	)
	err = db.Where("id in (?)", ids).Find(&listMenus).Error
	return listMenus, err
}
